package cn.tedu.pet.passport.service.impl;



import cn.tedu.pet.passport.ex.ServiceException;
import cn.tedu.pet.passport.mapper.PermissionMapper;
import cn.tedu.pet.passport.mapper.RolePermissionMapper;
import cn.tedu.pet.passport.pojo.entity.Admin;
import cn.tedu.pet.passport.pojo.entity.AdminRole;
import cn.tedu.pet.passport.pojo.entity.Permission;
import cn.tedu.pet.passport.pojo.entity.RolePermission;
import cn.tedu.pet.passport.pojo.param.PermissionAddNewParam;
import cn.tedu.pet.passport.pojo.param.PermissionUpdateInfoParam;
import cn.tedu.pet.passport.pojo.vo.PageData;
import cn.tedu.pet.passport.pojo.vo.PermissionListItemVO;

import cn.tedu.pet.passport.service.IPermissionService;
import cn.tedu.pet.passport.util.PageInfoToPageDataConverter;
import cn.tedu.pet.passport.web.ServiceCode;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;


@Slf4j
@Service
public class PermissionServiceImpl implements IPermissionService {

    @Autowired
    private PermissionMapper permissionMapper;
    @Autowired
    private RolePermissionMapper rolePermissionMapper;
    
    @Override
    public PageData<PermissionListItemVO> list(Integer pageNum) {
        Integer pageSize = 10;
        return list(pageNum, pageSize);
    }

    @Override
    public PageData<PermissionListItemVO> list(Integer pageNum, Integer pageSize) {
        log.debug("开始处理【查询权限列表】的业务，页码：{}，每页记录数：{}", pageNum, pageSize);
        PageHelper.startPage(pageNum, pageSize);
        List<PermissionListItemVO> list =permissionMapper.list();
        PageInfo<PermissionListItemVO> pageInfo = new PageInfo<>(list);
        PageData<PermissionListItemVO> pageData = PageInfoToPageDataConverter.convert(pageInfo);
        log.debug("查询完成，即将返回：{}", pageData);
        return pageData;
    }

    @Override
    public void addNew(PermissionAddNewParam permissionAddNewParam) {
        log.debug("开始处理【添加权限】的业务，参数：{}", permissionAddNewParam);
        // 检查权限用户名是否被占用，如果被占用，则抛出异常
        QueryWrapper<Permission> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name", permissionAddNewParam.getName());
        int countByUsername = permissionMapper.selectCount(queryWrapper);
        log.debug("根据权限名统计匹配的权限数量，结果：{}", countByUsername);
        if (countByUsername > 0) {
            String message = "添加权限失败，权限名已经被占用！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
        }
        Permission permission = new Permission();
        BeanUtils.copyProperties(permissionAddNewParam,permission);
        permission.setGmtCreate(LocalDateTime.now());
        permission.setGmtModified(LocalDateTime.now());
        permissionMapper.insert(permission);
        log.debug("将新的权限数据插入到数据库，完成！");


        Long [] roleIds =permissionAddNewParam.getRoleIds();
        RolePermission[] rolePermissions =new RolePermission[roleIds.length];
        for (int i = 0; i <rolePermissions.length ; i++) {
            RolePermission rolePermission =new RolePermission();
            rolePermission.setRoleId(roleIds[i]);
            rolePermission.setPermissionId(permission.getId());
            rolePermission.setGmtCreate(LocalDateTime.now());
            rolePermission.setGmtModified(LocalDateTime.now());
            rolePermissions[i]=rolePermission;
        }
        rolePermissionMapper.insertBatch(rolePermissions);
    }

    @Override
    public void deleteById(Long permissionId) {
        log.debug("开始处理【根据ID删除权限】的业务，参数：{}",permissionId);
        QueryWrapper<Permission> queryWrapper =new QueryWrapper<>();
        queryWrapper.eq("id", permissionId);
        int countById =permissionMapper.selectCount(queryWrapper);
        log.debug("根据管理员ID统计匹配的权限数量，结果：{}", countById);
        if(countById==0){
            String message = "删除权限失败，权限ID不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,message);
        }
        log.debug("开始处理【根据ID删除权限与角色相关】的业务，参数：{}",permissionId);
        QueryWrapper<RolePermission> queryWrapper1 =new QueryWrapper<>();
        queryWrapper1.eq("permission_id",permissionId);
        countById=rolePermissionMapper.selectCount(queryWrapper1);
        int deleteByID = rolePermissionMapper.deleteByPermissionId(permissionId);
        if(countById!=deleteByID){
            String message = "删除权限与角色相关失败，服务器忙，请稍后再尝试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_DELETE, message);
        }
        log.debug("即将执行删除数据，参数：{}", permissionId);
        int rows = permissionMapper.deleteById(permissionId);
        if (rows != 1) {
            String message = "删除权限失败，服务器忙，请稍后再尝试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_DELETE, message);
        }
    }

    @Override
    public void updateInfoById(Long id, PermissionUpdateInfoParam permissionUpdateInfoParam) {
        log.debug("开始处理【修改权限详情】的业务，ID：{}, 新数据：{}",id, permissionUpdateInfoParam);
        // 检查管理员是否存在，如果不存在，则抛出异常
        QueryWrapper<Permission> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id",id );
        int countById = permissionMapper.selectCount(queryWrapper);
        log.debug("根据权限ID统计匹配的权限数量，结果：{}", countById);
        if (countById == 0) {
            String message = "修改权限详情失败，权限数据不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }

        QueryWrapper<Permission> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.eq("name", permissionUpdateInfoParam.getName())
                .ne("id",id);
        int count = permissionMapper.selectCount(queryWrapper2);
        log.debug("根据权限名称统计匹配的权限数量，结果：{}", count);
        if (count > 0) {
            String message = "修改权限详情失败，权限名称已经被占用！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
        }


        QueryWrapper<RolePermission> queryWrapper3 =new QueryWrapper<>();
        queryWrapper3.eq("permission_id",id);
        countById=rolePermissionMapper.selectCount(queryWrapper3);

        int deleteByID = rolePermissionMapper.deleteByPermissionId(id);
        if(countById!=deleteByID){
            String message = "删除权限与角色相关失败，服务器忙，请稍后再尝试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_DELETE, message);
        }

        Permission permission =new Permission();
        BeanUtils.copyProperties(permissionUpdateInfoParam,permission);
        permission.setId(id);
        int rows =permissionMapper.updateById(permission);
        if (rows != 1) {
            String message = "修改权限详情失败，服务器忙，请稍后再试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_UPDATE, message);
        }
        log.debug("将新的权限数据更新入到数据库，完成！");


        Long [] roleIds =permissionUpdateInfoParam.getRoleIds();
        RolePermission[] rolePermissions =new RolePermission[roleIds.length];
        for (int i = 0; i <rolePermissions.length ; i++) {
            RolePermission rolePermission =new RolePermission();
            rolePermission.setRoleId(roleIds[i]);
            rolePermission.setPermissionId(permission.getId());
            rolePermission.setGmtCreate(LocalDateTime.now());
            rolePermission.setGmtModified(LocalDateTime.now());
            rolePermissions[i]=rolePermission;
        }
        rolePermissionMapper.insertBatch(rolePermissions);

    }

    @Override
    public  PageData<PermissionListItemVO> getListById(Long id) {
        log.debug("开始处理【查询管理员权限列表】的业务" );
        PageHelper.startPage(1, 50);
        List<PermissionListItemVO> list =permissionMapper.getListById(id);
        PageInfo<PermissionListItemVO> pageInfo = new PageInfo<>(list);
        PageData<PermissionListItemVO> pageData = PageInfoToPageDataConverter.convert(pageInfo);
        log.debug("查询完成，即将返回：{}", pageData);
        return pageData;

    }

    @Override
    public PermissionListItemVO getStandardById(Long id) {
        PermissionListItemVO permissionListItemVO =permissionMapper.getStandardById(id);
        return permissionListItemVO;
    }
}
